﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Backend.Packets
{
    public class ServerEventPacket : IPacket
    {
        private string m_sMessage;
        private const short m_nPacketId = 2;
        private byte[] m_Buffer;
        private short m_nLength;

        public string Message
        {
            get
            {
                return m_sMessage;
            }
            set
            {
                m_sMessage = value;
            }
        }

        public ServerEventPacket()
        {
        }

        public byte[] Pack()
        {
            MemoryStream MemBuffer = new MemoryStream();
            BinaryWriter Writer = new BinaryWriter(MemBuffer);

            Data = Encoding.ASCII.GetBytes(m_sMessage);

            Length = (short)(10 + Data.Length);

            Writer.Write((short)Length);
            Writer.Write((short)m_nPacketId);
            MemBuffer.Position += 6;

            Writer.Write(Data);

            MemBuffer.Capacity = Length;

            return MemBuffer.GetBuffer();
        }

        public void Load(byte[] Buffer)
        {
            MemoryStream MemBuffer = new MemoryStream(Buffer);
            BinaryReader Reader = new BinaryReader(MemBuffer);

            Length = Reader.ReadInt16();
            MemBuffer.Position += 8;

            Data = Reader.ReadBytes(Length - 10);

            Message = Encoding.ASCII.GetString(Data);
        }

        public byte[] Data
        {
            get
            {
                return m_Buffer;
            }
            set
            {
                m_Buffer = value;
            }
        }

        public short Length
        {
            get
            {
                return m_nLength;
            }
            set
            {
                m_nLength = value;
            }
        }
    }
}
